home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 1 / Atari Mega Archive - Volume 1.iso / language / dl_exsrc.zoo / strrpl.c < prev    next >
C/C++ Source or Header  |  1994-07-02  |  1KB  |  44 lines

  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include "extras.h"
  4.  
  5. int strrpl(string, ptrn, rpl, n)
  6.   char *string, *ptrn, *rpl;
  7.   int n;
  8. {
  9.   register char *s, *t = string;
  10.   char *u;
  11.   register int count = 0;
  12.   register char ptrn_1;
  13.   int ptrn_len = strlen(ptrn), rpl_len = strlen(rpl);
  14.   int store_len;
  15.  
  16.   if (!string || *string == '\0' || !ptrn || *ptrn == '\0' || n == 0)
  17.     return 0;
  18.  
  19.   /* At worst, the string's size could increase by a factor of
  20.      rpl_len/ptrn_len */
  21.   if (rpl_len > ptrn_len)
  22.     store_len = (strlen(string)/ptrn_len + 1) * rpl_len + 1;
  23.   else
  24.     store_len = strlen(string) + 1;
  25.  
  26.   s = u = (char *)malloc((size_t)store_len);
  27.   ptrn_1 = *ptrn;
  28.   for (;;) {
  29.     if (*t == '\0') {
  30.       *s = '\0';
  31.       break;
  32.     } else if (*t == ptrn_1 && strncmp(t, ptrn, ptrn_len) == 0 &&
  33.            (n < 0 || count < n)) {
  34.       strcpy(s, rpl);
  35.       s += rpl_len;
  36.       t += ptrn_len;
  37.       count++;
  38.     } else *s++ = *t++;
  39.   }
  40.   strcpy(string, u);
  41.   free(u);
  42.   return count;
  43. }
  44.